<template>
  <div id="app">
    {{time}}
    <br>
    {{formatTime(time)}}
    <br>
    {{formatTime(time,'Y年m月d日 H:i:s')}}
    <!-- vue2  过滤器写法 -->
    <h2>
      {{time|formatTime2('Y年m月d日 H:i:s')}}
    </h2>
  </div>
</template>

<script>
export default{
  data(){
    return {
      time:Date.now()
    }
  },
  methods:{
    formatTime(time,formatStr='YYYY-m-d H:i:s'){
      let date=new Date(time);
      let dMap={
        Y:date.getFullYear(),
        d:date.getDate(),
        m:date.getMonth()+1,
        H:date.getHours(),
        i:date.getMinutes(),
        s:date.getSeconds()
      }
      for(let k in dMap){
        let reg=new RegExp(k+"+",'gi');//全局匹配忽略大小写
        formatStr=formatStr.replace(reg,dMap[k]);
      }
      return formatStr;
    }
  },
  filters:{
    formatTime2(time,formatStr='YYYY-m-d H:i:s'){
      let date=new Date(time);
      let dMap={
        Y:date.getFullYear(),
        d:date.getDate(),
        m:date.getMonth()+1,
        H:date.getHours(),
        i:date.getMinutes(),
        s:date.getSeconds()
      }
      for(let k in dMap){
        let reg=new RegExp(k+"+",'gi');//全局匹配忽略大小写
        formatStr=formatStr.replace(reg,dMap[k]);
      }
      return formatStr;
    }
  }
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>
